/**
 * Created by superman on 17/2/16.
 * http配置
 */

import axios from 'axios'
import store from '@/vuex'
import * as types from '@/vuex/types'
import router from '@/router'
// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'https://mxcard.maoxiu.org';
axios.defaults.headers = {
    'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
// http request 添加请求拦截器
axios.interceptors.request.use(
    config => {
        //如果token 存在则添加所有请求header
        if (store.state.login.token) {
            config.headers.Authorization = `token ${store.state.login.token}`;
        }
        //console.log(`${store.state.login.token}`)
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 添加响应拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {

            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    store.commit('login/'+types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error.response.data)
    });

export default axios;
